package com.example.shoporder.service.impl;

import com.example.shopcommon.dao.entity.Order;
import com.example.shopcommon.dao.entity.Product;
import com.example.shopcommon.dao.entity.User;
import com.example.shopcommon.feign.ProductFeignClient;
import com.example.shopcommon.feign.UserFeignClient;
import com.example.shopcommon.mq.TopicConstant;
import com.example.shoporder.dao.OrderDao;
import com.example.shoporder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public Order create(Long userId, Long pid, int orderCount) {

        Product product  = productFeignClient.get(pid);
        // 定单总价 = 订购数量(count) * 商品单价(100)
        BigDecimal orderMoney = product.getProductPrice().multiply(BigDecimal.valueOf(orderCount));

        User user = userFeignClient.get(userId);

        Order order = new Order();
        order.setUid(userId);
        order.setUsername(user.getUsername());
        order.setProductName(product.getProductName());
        order.setPid(pid);
        order.setNumber(orderCount);
        order.setProductPrice(orderMoney);
        orderDao.save(order);

        //模拟延迟
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 调用账户余额扣减
        User reductUser = new User();
        reductUser.setId(userId);
        reductUser.setMoney(orderMoney);
        String result = userFeignClient.reduce(reductUser);
        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException("Failed to call Account Service. ");
        }

        //下单成功之后,将消息放到mq中
        rocketMQTemplate.convertAndSend(TopicConstant.ORDER_TOPIC, order);

        return order;
    }

}
